<template>
	<view class="container">
		<!-- 用户信息栏 -->
		<view class="user-info-card">
			<view class="user-avatar">
				<text class="avatar-text">{{ userNickname?.charAt(0) || 'U' }}</text>
			</view>
			<view class="user-details">
				<text class="user-name">{{ userNickname || '用户' }}</text>
				<text class="user-id">ID: {{ userId }}</text>
			</view>
			<button class="logout-btn" @tap="logout">
				<text class="logout-icon">↗</text>
			</button>
		</view>

		<!-- 设备状态卡片 -->
		<view class="status-card">
			<view class="status-header">
				<text class="status-title">设备状态</text>
				<view class="status-badge" :class="pushStatusClass">
					{{ pushStatus }}{{pushStatusClass}}
				</view>
			</view>
			<view class="cid-display">
				<text class="cid-label">设备CID:</text>
				<text class="cid-value">{{ cid || '获取中...' }}</text>
				<button class="copy-btn" @tap="copyCid" v-if="cid">📋</button>
			</view>
		</view>

		<!-- 发送推送卡片 -->
		<view class="send-card">
			<view class="card-header">
				<text class="card-title">发送推送消息</text>
				<text class="card-subtitle">向指定设备发送通知</text>
			</view>

			<view class="form-container">
				<view class="input-group">
					<text class="input-label">目标设备CID</text>
					<input v-model="targetCid" placeholder="粘贴或输入目标CID" class="modern-input" maxlength="100" />
					<button class="paste-btn" @tap="pasteFromClipboard">粘贴</button>
				</view>

				<view class="input-group">
					<text class="input-label">消息标题</text>
					<input v-model="pushTitle" placeholder="请输入消息标题" class="modern-input" maxlength="50" />
				</view>

				<view class="input-group">
					<text class="input-label">消息内容</text>
					<textarea v-model="pushContent" placeholder="请输入详细消息内容..." class="modern-textarea" maxlength="200"
						auto-height />
				</view>

				<button class="send-action-btn" @tap="sendPush" :disabled="!targetCid || !pushTitle || !pushContent"
					:class="{ 'disabled': !targetCid || !pushTitle || !pushContent }">
					<text class="btn-text">发送推送</text>
					<text class="btn-icon">🚀</text>
				</button>
			</view>
		</view>

		<!-- 消息列表卡片 -->
		<view class="messages-card">
			<view class="card-header">
				<text class="card-title">消息记录</text>
				<view class="message-count">{{ messages.length }}</view>
			</view>
			{{messages}}
			<scroll-view class="messages-list" scroll-y>
				<view v-for="(msg, index) in messages" :key="index" class="message-item-modern">
					<view class="message-avatar">
						<text class="avatar-icon">📱</text>
					</view>
					<view class="message-content-modern">
						<view class="message-header-modern">
							<text class="message-title-modern">{{ msg.title || '系统通知' }}</text>
							<text class="message-time-modern">{{ formatTime(msg.time) }}</text>
						</view>
						<text class="message-text-modern">{{ msg.content }}</text>
						<view class="message-payload-modern" v-if="msg.payload">
							<text class="payload-text">附加数据: {{ JSON.stringify(msg.payload) }}</text>
						</view>
					</view>
				</view>

				<view class="empty-state" v-if="messages.length === 0">
					<text class="empty-icon">📭</text>
					<text class="empty-text">暂无消息记录</text>
					<text class="empty-subtext">收到推送后会在这里显示</text>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				cid: '', // 本设备CID
				pushStatus: '未初始化',
				userId: '', // 当前登录用户ID
				userNickname: '', // 用户昵称
				messages: [], // 接收的消息
				targetCid: '', // 目标接收者CID
				pushTitle: '', // 推送标题
				pushContent: '' // 推送内容
			};
		},

		onLoad() {
			// 检查是否已登录
			const userInfo = uni.getStorageSync('userInfo');
			if (!userInfo || !userInfo.userId) {
				uni.redirectTo({
					url: '/pages/login/index'
				});
				return;
			}

			this.userId = userInfo.userId;
			this.userNickname = userInfo.nickname;
			this.initPushService();
			this.loadHistoryMessages();
			// 注册通知点击事件监听
			uni.getChannelManager();
			uni.onPushMessage((res) => {
				console.log('收到推送消息:', res);

				// 根据 type 处理不同场景
				switch (res.type) {
					case 'receive':
						// 应用前台接收通知消息：可手动显示弹窗提示
						this.handleForegroundNotification(res.data);
						break;

					case 'click':
						// 用户点击通知栏消息：处理跳转逻辑
						this.handleNotificationClick(res.data);
						break;

					case 'transmission':
						// 透传消息：自定义处理（如静默更新数据）
						this.handleTransmissionMessage(res.data);
						break;

					default:
						this.handleReceivedMessage(res);
						console.log('其他消息类型:', res.type);
				}
			});
		},

		methods: {
			// 初始化推送服务（原有逻辑保留）
			initPushService() {
				const platform = uni.getSystemInfoSync().platform;
				if (platform === 'devtools') {
					this.pushStatus = '请在真机测试';
					return;
				}
				this.pushStatus = '初始化中...';

				// 获取本设备CID
				uni.getPushClientId({
					success: (res) => {
						this.cid = res.cid;
						this.pushStatus = '已就绪';
						console.log('本设备CID:', this.cid);
						this.targetCid = res.cid;
						// 改用云函数上传CID（优化点）
						this.uploadCidToServer();
					},
					fail: (err) => {
						this.pushStatus = '获取CID失败';
						console.error('获取CID失败:', err);
					}
				});
			},

			// 新增：调用云函数发送推送
			sendPush() {
				uni.showLoading({
					title: '发送中...'
				});

				// 调用云函数发送推送
				uniCloud.callFunction({
					name: 'myPush', // 对应云函数名称
					data: {
						cid: this.targetCid, // 目标接收者CID
						title: this.pushTitle, // 消息标题
						content: this.pushContent, // 消息内容
						messageType: 'notification', // 明确指定为通知消息
						payload: {
							sender: this.cid, // 附加发送者CID
							time: new Date().getTime()
						}
					}
				}).then(res => {
					uni.hideLoading();
					console.log('推送结果:', res.result);
					if (res.result.success) {
						uni.showToast({
							title: '推送成功',
							icon: 'success'
						});
						// 清空表单
						this.pushTitle = '';
						this.pushContent = '';
					} else {
						uni.showToast({
							title: '推送失败: ' + (res.result.message || '未知错误'),
							icon: 'none'
						});
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('调用云函数失败:', err);
					uni.showToast({
						title: '调用失败',
						icon: 'none'
					});
				});
			},

			// 优化：改用云函数上传CID（替代uni.request）
			uploadCidToServer() {
				const userId = this.userId;

				uniCloud.callFunction({
					name: 'bind-cid', // 新增一个绑定CID的云函数
					data: {
						userId,
						cid: this.cid
					}
				}).then(res => {
					console.log('CID绑定结果:', res.result);
				}).catch(err => {
					console.error('CID绑定失败:', err);
					setTimeout(() => this.uploadCidToServer(), 5000); // 重试
				});
			},
			// 处理前台接收的通知（应用打开时）
			handleForegroundNotification(data) {
				// 显示弹窗提示（避免与系统通知栏冲突）
				console.log("handleForegroundNotification", data);
				uni.showModal({
					title: data.title,
					content: data.content,
					showCancel: false,
					confirmText: '收到'
				});
				uni.createPushMessage(data);
				uni.setAppBadgeNumber(1);
				// 同时将消息添加到本地列表
				this.messages.unshift({
					title: data.title,
					content: data.content,
					payload: data.payload,
					time: new Date().getTime()
				});
				this.saveHistoryMessages();
			},

			// 处理通知点击事件（点击通知栏消息）
			handleNotificationClick(data) {
				// 示例：根据 payload 跳转页面
				if (data.payload && data.payload.path) {
					uni.navigateTo({
						url: data.payload.path
					});
				}
				// 将消息添加到本地列表
				this.messages.unshift({
					title: data.title,
					content: data.content,
					payload: data.payload,
					time: new Date().getTime()
				});
				this.saveHistoryMessages();
			},

			// 处理透传消息（非通知消息）
			handleTransmissionMessage(data) {
				// 透传消息无 title/content，需解析自定义数据
				uni.showToast({
					title: '收到新消息',
					icon: 'none'
				});
				console.log('透传数据:', data.payload);
			},
			// 原有消息处理逻辑保留
			handleReceivedMessage(res) {
				let message = {
					time: new Date().getTime()
				};

				if (res.type === 'transmission' && res.content) {
					try {
						message = {
							...message,
							...JSON.parse(res.content)
						};
					} catch (e) {
						message.content = res.content;
					}
				}

				if (res.type === 'notification') {
					message.title = res.title;
					message.content = res.content;
					if (res.payload) {
						try {
							message.payload = JSON.parse(res.payload);
						} catch (e) {
							message.payload = res.payload;
						}
					}
				}
				if (res.type === 'receive') {
					message.title = res.data.title;
					message.content = res.data.content;
					if (res.data.payload) {
						try {
							message.payload = JSON.parse(res.data.payload);
						} catch (e) {
							message.payload = res.data.payload;
						}
					}
				}
				this.messages.unshift(message);
				this.saveHistoryMessages();
				uni.showToast({
					title: '收到新消息',
					icon: 'none'
				});
			},

			// 通知点击事件处理（原有逻辑保留）
			handleNotificationClick(res) {
				if (res.payload) {
					try {
						const payload = JSON.parse(res.payload);
						if (payload.page) {
							uni.navigateTo({
								url: payload.page
							});
						}
					} catch (e) {
						console.error('解析点击数据失败:', e);
					}
				}
			},
			// 原有存储相关方法保留
			saveHistoryMessages() {
				try {
					uni.setStorageSync('pushMessages', this.messages);
				} catch (e) {
					console.error('保存消息失败:', e);
				}
			},
			loadHistoryMessages() {
				try {
					const savedMessages = uni.getStorageSync('pushMessages');
					this.messages = savedMessages && Array.isArray(savedMessages) ? savedMessages : [];
				} catch (e) {
					console.error('加载消息失败:', e);
					this.messages = [];
				}
			},
			formatTime(timestamp) {
				return new Date(timestamp).toLocaleString();
			}
		},
		// 复制CID到剪贴板
		copyCid() {
			uni.setClipboardData({
				data: this.cid,
				success: () => {
					uni.showToast({
						title: 'CID已复制',
						icon: 'success'
					});
				}
			});
		},

		// 从剪贴板粘贴
		async pasteFromClipboard() {
			try {
				const data = await uni.getClipboardData();
				this.targetCid = data.data || '';
			} catch (e) {
				uni.showToast({
					title: '获取剪贴板失败',
					icon: 'none'
				});
			}
		},

		// 计算状态样式类
		pushStatusClass() {
			if (this.pushStatus.includes('已就绪')) return 'ready';
			if (this.pushStatus.includes('初始化')) return 'loading';
			if (this.pushStatus.includes('失败')) return 'error';
			return '';
		},
		logout() {
			uni.showModal({
				title: '提示',
				content: '确定要退出登录吗？',
				success: (res) => {
					if (res.confirm) {
						uni.removeStorageSync('userInfo');
						uni.removeStorageSync('userId');
						uni.redirectTo({
							url: '/pages/login/index'
						});
					}
				}
			});
		}
	};
</script>


<style lang="scss" scoped>
	// 全局样式变量
	$primary-color: #667eea;
	$secondary-color: #764ba2;
	$success-color: #4CAF50;
	$warning-color: #FF9800;
	$error-color: #f44336;
	$text-primary: #333;
	$text-secondary: #666;
	$text-light: #999;
	$bg-light: #f8f9fa;
	$border-color: #e1e5e9;
	$shadow-light: 0 2px 12px rgba(0, 0, 0, 0.08);
	$shadow-medium: 0 4px 20px rgba(0, 0, 0, 0.12);
	$border-radius: 16rpx;

	.container {
		min-height: 100vh;
		background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
		padding: 20rpx;
	}

	// 用户信息卡片
	.user-info-card {
		background: white;
		border-radius: $border-radius;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: $shadow-light;
		display: flex;
		align-items: center;

		.user-avatar {
			width: 80rpx;
			height: 80rpx;
			background: linear-gradient(135deg, $primary-color, $secondary-color);
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-right: 20rpx;

			.avatar-text {
				color: white;
				font-size: 32rpx;
				font-weight: bold;
			}
		}

		.user-details {
			flex: 1;

			.user-name {
				display: block;
				font-size: 32rpx;
				font-weight: bold;
				color: $text-primary;
			}

			.user-id {
				display: block;
				font-size: 24rpx;
				color: $text-secondary;
				margin-top: 4rpx;
			}
		}

		.logout-btn {
			width: 60rpx;
			height: 60rpx;
			background: rgba($error-color, 0.1);
			border: none;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;

			.logout-icon {
				color: $error-color;
				font-size: 28rpx;
			}
		}
	}

	// 状态卡片
	.status-card {
		background: white;
		border-radius: $border-radius;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: $shadow-light;

		.status-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;

			.status-title {
				font-size: 28rpx;
				font-weight: bold;
				color: $text-primary;
			}

			.status-badge {
				padding: 8rpx 16rpx;
				border-radius: 20rpx;
				font-size: 24rpx;
				font-weight: bold;

				&.ready {
					background: rgba($success-color, 0.1);
					color: $success-color;
				}

				&.loading {
					background: rgba($warning-color, 0.1);
					color: $warning-color;
				}

				&.error {
					background: rgba($error-color, 0.1);
					color: $error-color;
				}
			}
		}

		.cid-display {
			display: flex;
			align-items: center;
			flex-wrap: wrap;

			.cid-label {
				font-size: 24rpx;
				color: $text-secondary;
				margin-right: 10rpx;
			}

			.cid-value {
				font-size: 24rpx;
				color: $text-primary;
				font-family: monospace;
				background: $bg-light;
				padding: 8rpx 12rpx;
				border-radius: 8rpx;
				flex: 1;
				word-break: break-all;
			}

			.copy-btn {
				margin-left: 10rpx;
				padding: 8rpx 12rpx;
				font-size: 20rpx;
				background: $bg-light;
				border: none;
				border-radius: 8rpx;
			}
		}
	}

	// 发送卡片
	.send-card {
		background: white;
		border-radius: $border-radius;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: $shadow-light;

		.card-header {
			margin-bottom: 30rpx;

			.card-title {
				font-size: 32rpx;
				font-weight: bold;
				color: $text-primary;
				display: block;
			}

			.card-subtitle {
				font-size: 24rpx;
				color: $text-secondary;
				margin-top: 8rpx;
			}
		}

		.form-container {
			.input-group {
				margin-bottom: 24rpx;

				.input-label {
					display: block;
					font-size: 28rpx;
					color: $text-primary;
					margin-bottom: 12rpx;
					font-weight: 500;
				}

				.modern-input {
					width: 100%;
					height: 80rpx;
					padding: 0 20rpx;
					border: 2rpx solid $border-color;
					border-radius: 12rpx;
					font-size: 28rpx;
					transition: all 0.3s ease;

					&:focus {
						border-color: $primary-color;
						box-shadow: 0 0 0 3rpx rgba($primary-color, 0.1);
					}
				}

				.modern-textarea {
					width: 100%;
					min-height: 120rpx;
					padding: 20rpx;
					border: 2rpx solid $border-color;
					border-radius: 12rpx;
					font-size: 28rpx;
					transition: all 0.3s ease;

					&:focus {
						border-color: $primary-color;
						box-shadow: 0 0 0 3rpx rgba($primary-color, 0.1);
					}
				}

				.paste-btn {
					position: absolute;
					right: 10rpx;
					top: 50%;
					transform: translateY(-50%);
					padding: 8rpx 16rpx;
					font-size: 24rpx;
					background: $bg-light;
					border: none;
					border-radius: 8rpx;
					color: $text-secondary;
				}
			}

			.send-action-btn {
				width: 100%;
				height: 88rpx;
				background: linear-gradient(135deg, $primary-color, $secondary-color);
				color: white;
				border: none;
				border-radius: 44rpx;
				font-size: 32rpx;
				font-weight: bold;
				display: flex;
				align-items: center;
				justify-content: center;
				gap: 10rpx;
				transition: all 0.3s ease;

				&:active {
					transform: scale(0.98);
				}

				&.disabled {
					background: #ccc;
					cursor: not-allowed;
					transform: none;
				}

				.btn-text {
					font-size: 32rpx;
				}

				.btn-icon {
					font-size: 28rpx;
				}
			}
		}
	}

	// 消息列表卡片
	.messages-card {
		background: white;
		border-radius: $border-radius;
		padding: 30rpx;
		box-shadow: $shadow-light;

		.card-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;

			.card-title {
				font-size: 32rpx;
				font-weight: bold;
				color: $text-primary;
			}

			.message-count {
				background: $primary-color;
				color: white;
				padding: 4rpx 12rpx;
				border-radius: 20rpx;
				font-size: 24rpx;
				font-weight: bold;
			}
		}

		.messages-list {
			max-height: 600rpx;

			.message-item-modern {
				display: flex;
				padding: 20rpx 0;
				border-bottom: 1rpx solid $border-color;

				&:last-child {
					border-bottom: none;
				}

				.message-avatar {
					width: 80rpx;
					height: 80rpx;
					background: linear-gradient(135deg, $primary-color, $secondary-color);
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-right: 20rpx;
					flex-shrink: 0;

					.avatar-icon {
						font-size: 40rpx;
					}
				}

				.message-content-modern {
					flex: 1;

					.message-header-modern {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-bottom: 8rpx;

						.message-title-modern {
							font-size: 28rpx;
							font-weight: bold;
							color: $text-primary;
						}

						.message-time-modern {
							font-size: 24rpx;
							color: $text-light;
						}
					}

					.message-text-modern {
						font-size: 26rpx;
						color: $text-secondary;
						line-height: 1.5;
						margin-bottom: 8rpx;
					}

					.message-payload-modern {
						.payload-text {
							font-size: 22rpx;
							color: $text-light;
							background: $bg-light;
							padding: 4rpx 8rpx;
							border-radius: 4rpx;
						}
					}
				}
			}

			.empty-state {
				text-align: center;
				padding: 80rpx 0;

				.empty-icon {
					font-size: 80rpx;
					display: block;
					margin-bottom: 20rpx;
				}

				.empty-text {
					font-size: 28rpx;
					color: $text-secondary;
					display: block;
					margin-bottom: 10rpx;
				}

				.empty-subtext {
					font-size: 24rpx;
					color: $text-light;
				}
			}
		}
	}

	// 响应式布局
	@media screen and (max-width: 750rpx) {
		.container {
			padding: 10rpx;
		}
	}
</style>